<?php

namespace app\company\controller;

use app\admin\model\GoodsCate;
use app\admin\model\GoodsRule;
use app\admin\model\GoodsSpec;
use app\company\model\CompanyGoodsStore;
use app\company\validate\CompanyGoodsValidate;
use app\mini\model\StoreOrderDetail;
use app\service\traits\Crud;
use app\company\model\CompanyGoods as CompanyGoodsModel;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Response;
use app\company\model\CompanyGoodsRule;
use app\company\model\CompanyOrderStorage;
use app\company\model\CompanyGoodsRate;
use app\company\model\Store;


class CompanyGoods extends Base
{
    private CompanyGoodsModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new CompanyGoodsModel();
        $this->validateClass = CompanyGoodsValidate::class;
        $this->field         = 'id,goods_id,company_id,goods_cate_id,descriptions,status,racking_time,sold_out_time';
        $this->withSearch    = 'id,goods_id,company_id,status,goods_cate_id';
        $this->isGs          = true;
    }

    public function format($list): mixed
    {
        return $list->each(function ($item) {
            $item->goods_cate_name = getGoodsCateName($item->goods_cate_id);
            $item->goods           = $item->goods()->field('id,img,name,unit,no,shelf_life,spec_type,min_code,max_code')->find();
            $item->rule            = GoodsRule::where('goods_id',$item->goods->id)->find();
            $item->stock           = CompanyOrderStorage::where('goods_id', $item->goods_id)->gs()->sum('quantity');   //库存 所有规格之和(产品定义)
            //销量
            $item->sales = StoreOrderDetail::hasWhere('storeOrder', function ($query) {
                $query->whereIn('order_status', [2, 3, 4])->gs();
            })->where('goods_id', $item->goods_id)->sum('quantity');
        });
    }


    public function detailFormat($info): mixed
    {
        $info->goods_spec      = GoodsSpec::where('goods_id', $info->goods_id)->field('id,name,value')->select();
        $info->goods_cate_name = getGoodsCateName($info->goods_cate_id);
        $info->goods           = $info->goods()->field('id,img,name,unit,no,shelf_life,spec_type')->find();
        $info->goods_rule      = CompanyGoodsRule::seekGoods($info->company_id, $info->goods_id)->field('id,goods_rule_id,money')->select()->each(function ($item) {
            $filed            = 'id,spec_name,img,purchasing_price,weight';
            $item->goods_rule = $item->goodsRule()->withTrashed()->field($filed)->find();
            //销量
            $item->sales = (int)redis()->zScore(xsGoodsRuleKey() . $this->company_id, $item->goods_rule_id);
        });
        //费率
        $info->rate = CompanyGoodsRate::where('company_id', $info->company_id)->where('goods_id', $info->goods_id)->find();
        return $info;
    }


    /**
     * 筛选框
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function search(): Response
    {
        $name = request()->param('name', '');
        $sql  = $this->model;
        $list = $sql->with('goods')->hasWhere('goods', function ($query) use ($name) {
            $query->where('name', 'like', '%' . $name . '%');
        })->gs($this->company_id)->select();
        return $this->success('获取成功', compact('list'));
    }

    /**
     * 公司-商品-门店列表 此功能已废弃 对应关系已发生变更 ,门店商品根据所属第三方直接判定
     * @param $company_goods_id
     * @return Response
     */
    public function goodsStore($company_goods_id): Response
    {
        $is_all_channel = (int)$this->model->where('id', $company_goods_id)->value('is_all_channel');
        $list           = [];
        if ($is_all_channel == 2) {
            $list = CompanyGoodsStore::where('company_goods_id', $company_goods_id)->column('store_id');
        }
        return $this->success('获取成功', compact('list', 'is_all_channel'));
    }


    /**
     * 公司-商品-绑定门店 此功能已废弃 对应关系已发生变更 ,门店商品根据所属第三方直接判定
     * @param $company_goods_id
     * @param $is_all_channel
     * @param string $store_ids
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function goodsBindStore($company_goods_id, $is_all_channel, string $store_ids = ""): Response
    {
        $goods = \app\mini\model\CompanyGoods::where('id', $company_goods_id)->find();
        if (!$goods) return $this->error('商品不存在');
        $goods->is_all_channel = $is_all_channel;
        $goods->save();//更新是否全渠道
        //删除已存在的绑定关系
        CompanyGoodsStore::where('company_goods_id', $company_goods_id)->select()->delete();
        //当是全渠道时,绑定所有门店
        if ($is_all_channel == 1) {
            $store_ids = Store::where('company_id', $goods->company_id)->column('id');
            $store_ids = implode(',', $store_ids);
        }

        if ($store_ids) {
            $store_ids = explode(',', $store_ids);
            $data      = [];
            foreach ($store_ids as $store_id) {
                $arr['company_goods_id'] = $company_goods_id;
                $arr['store_id']         = $store_id;
                $arr['goods_id']         = $goods->goods_id;
                $arr['company_id']       = $goods->company_id;
                $data[]                  = $arr;
            }
            $data && (new CompanyGoodsStore)->saveAll($data);
        }
        return $this->success('更新成功');
    }


}